package com.test.util;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * xml工具类
 * 
 * @author menglili
 *
 */
public class XmlUtil {

	/**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
	 * 
	 * @param strxml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	public static <K, V> Map<K, V> doXMLParse(String strxml) throws JDOMException, IOException {
		strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

		if (null == strxml || "".equals(strxml)) {
			return null;
		}

		Map<K, V> m = new HashMap<K, V>();

		InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List<Element> list = root.getChildren();
		Iterator<Element> it = list.iterator();
		while (it.hasNext()) {
			Element e = (Element) it.next();
			K key = (K) e.getName();
			V val = null;
			List<Element> children = e.getChildren();
			if (children.isEmpty()) {
				val = (V) e.getTextNormalize();
			} else {
				val = (V) XmlUtil.getChildrenText(children);
			}
			if (val != null && !val.toString().equals("")) {
				m.put(key, val);
			}
		}

		// 关闭流
		in.close();

		return m;
	}

	public static void main(String[] args) throws JDOMException, IOException {
		String res = "<?xml version=\"1.0\" encoding=\"gb2312\"?><Root><Result>1</Result><SendNum>2</SendNum></Root>";
		InputStream in = new ByteArrayInputStream(res.getBytes("UTF-8"));
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		System.out.println(root.getChildText("Result"));
		System.out.println(root.getChildText("SendNum"));

	}

	/**
	 * 获取子结点的xml
	 * 
	 * @param children
	 * @return String
	 */
	public static String getChildrenText(List<Element> children) {
		StringBuffer sb = new StringBuffer();
		if (!children.isEmpty()) {
			Iterator<Element> it = children.iterator();
			while (it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List<Element> list = e.getChildren();
				sb.append("<" + name + ">");
				if (!list.isEmpty()) {
					sb.append(XmlUtil.getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}

		return sb.toString();
	}

	public static <K, V> String map2XmlHasCDATA(Map<K, V> map, String... rootAlias) {
		if (map.isEmpty()) {
			return null;
		}
		StringBuilder xml = new StringBuilder();
		if (rootAlias == null || rootAlias.length == 0) {
			rootAlias = new String[] { "xml" };
		}
		xml.append("<").append(rootAlias[0]).append(">\n");
		Iterator<K> it = map.keySet().iterator();
		while (it.hasNext()) {
			K key = it.next();
			V val = map.get(key);
			xml.append("<").append(key).append(">");
			// xml.append("<![CDATA[").append(val).append("]]>");
			xml.append(val);
			xml.append("</").append(key).append(">\n");
		}

		xml.append("</").append(rootAlias[0]).append(">");
		return xml.toString();
	}

}
